<template>
  <el-upload
    class="avatar-uploader"
    action="/api/upload"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :show-file-list="false"
  >
    <img v-if="props.imageUrl" :src="props.imageUrl" class="avatar" />
    <div v-else class="avatar-uploader-icon">
      <Icon name="Plus" />
    </div>
  </el-upload>
</template>

<script lang="ts" setup>
import { defineProps } from "vue";
import { ElMessage } from "element-plus";
import Icon from "./Icon.vue";
import { UploadRawFile } from "element-plus/lib/components/upload/src/upload.js";
import { responseUploadData } from "@/api/returnData";

const props = defineProps({
  imageUrl: {
    type: String,
    default: "",
  },
  changeImageUrl: {
    type: Function,
    required: true,
  },
});

const handleAvatarSuccess = (response: responseUploadData) => {
  if (response.code != 0) {
    ElMessage.error(response.msg);
    return;
  }
  console.log(response.data);
  props.changeImageUrl(response.data);
};

// 上传前的操作
const beforeAvatarUpload = (rawFile: UploadRawFile) => {
  const imagesArr = [
    "image/jpeg",
    "image/webp",
    "image/png",
    "image/jpg",
    "image/gif",
    "image/pdf",
  ];
  if (!imagesArr.includes(rawFile.type)) {
    ElMessage.error("文件类型错误请重新上传！");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片上传大小超过2MB,无法上传!");
    return false;
  }

  return true;
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 150px;
  height: 150px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
